package com.jt.www.job.issue;

import com.jt.www.common.service.JobQueryListService;
import com.jt.www.dao.mapper.issue.mapper.IssuePolicyLogEntityMapper;
import com.jt.www.dao.mapper.issue.mapper.IssueRecordEntityMapper;
import com.jt.www.model.issue.entity.IssuePolicyLogEntity;
import com.jt.www.model.issue.entity.IssueRecordEntity;
import com.jt.www.util.DateUtils;
import com.jt.www.util.JsonUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.lang.reflect.Method;
import java.util.*;

import static com.jt.www.enums.issue.PolicyEnum.ZH_SZ_XZ_POLICY;

/*
 *  检查电子保单是否消费以及组装报文
 * @Author xq.wu
 * @Date 13:11 2020/4/6
 * @Param
 * @return
 **/

@Component
@EnableScheduling
public class CheckIssueMQRecordTaskTest implements SchedulingConfigurer {
    public static final Logger log = LoggerFactory.getLogger(CheckIssueMQRecordTaskTest.class);
    //初始化ifCode,  Method
    private static final Map<String, String> myMapMethod;

    static {
        myMapMethod = new HashMap<String, String>();
        myMapMethod.put("20190528001", "infoXmlHt");
        myMapMethod.put("20190528002", "infoXmlHt");
        myMapMethod.put("20190528003", "infoXmlHt");
        myMapMethod.put("20190516002", "infoXmlSD");
        myMapMethod.put("20190516006", "infoXmlYNFJ");
        myMapMethod.put("20190515002", "infoXmlXZANDSZ");
        myMapMethod.put("20190726012", "infoXmlXZANDSZ");
        myMapMethod.put("20190515026", "infoXmlXZ");
        myMapMethod.put("20190515006", "infoXmlAZBHS");
        myMapMethod.put("20190802002", "infoXmlSPX");
        myMapMethod.put("20190729001", "infoXmlXZXPX");
        myMapMethod.put("20190805001", "infoXmlEpolicy");
        myMapMethod.put("20190807001", "infoXmlEpolicy");
        myMapMethod.put("20190518001", "infoXmlSZXZDD");
        myMapMethod.put("20190726017", "infoXmlSZXZ");
        myMapMethod.put("20190731001", "infoXmlSZXZ");
        myMapMethod.put("20190802001", "infoXmlSPXTP");
    }

    @Autowired
    IssuePolicyLogEntityMapper issuePolicyLogEntityMapper;
    @Autowired
    IssueRecordEntityMapper issueRecordEntityMapper;
    @Autowired
    JobQueryListService jobQueryListService;

    /* *//**
     * 任务开关
     *//*
    @Value("${jtpf.issuemq.open}")
    private int checkOpen;

    *//**
     * 任务执行周期
     *//*
    @Value("${jtpf.issuemq.cron}")
    private String cron;// 每隔一分钟执行一次

    *//**
     *  单个服务器出单查询缓存失效时间 因不同的定时任务决定
     *//*
    private static final long ISSUE_MQ_TIME_OUT = 40L;

    */

    /**
     * 检查 电子保单是否消费的定时任务 缓存key
     *//*
    private static final String ISSUE_MQ_LOCK_KEY = "EDU_ISSUE_MQ";*/
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
      /*  if(checkOpen != 1) {
            return;
        }
        if (RedisUtil.setLock(ISSUE_MQ_LOCK_KEY, "1", ISSUE_MQ_TIME_OUT)) {
            Runnable task0 = () -> checkStart();
            Trigger trigger0 = triggerContext -> new CronTrigger(cron).nextExecutionTime(triggerContext);
            taskRegistrar.addTriggerTask(task0, trigger0);
        }*/
    }

    //查询未处理的列表
    public List<IssueRecordEntity> getIssueRecordList() {
        Weekend<IssueRecordEntity> weekend = Weekend.of(IssueRecordEntity.class);
        WeekendCriteria<IssueRecordEntity, Object> criteria = weekend.weekendCriteria();
        criteria.andEqualTo(IssueRecordEntity::getSendStatus, "1");//1:未处理
        criteria.andLessThan(IssueRecordEntity::getStatus, "2");//只有成功的处理
        List<IssueRecordEntity> resultList = jobQueryListService.getJobProcessIssueRecordList(weekend);
        return resultList;
    }

    //启动任务，循环执行
    private void checkStart() {
        String currentTime = DateUtils.getCurrentTime();
        log.info(currentTime + "CheckIssueMqRecordTask start,检查出单电子保单是否消费的任务开始...");
        List<IssueRecordEntity> issueRecordEntityList = getIssueRecordList();
        if (issueRecordEntityList != null && issueRecordEntityList.size() > 0) {
            for (IssueRecordEntity t : issueRecordEntityList) {
                splicingMessage(t);
            }
        }
        log.info(currentTime + "CheckIssueMqRecordTask end,检查出单电子保单是否消费的任务结束...");
    }

    //组装报文
    public void splicingMessage(IssueRecordEntity t) {
        String currentTime = DateUtils.getCurrentTime();
        // 消费  ： 需要组织报文，去调用接口
        IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
        String consumeStatus = "1";
        issuePolicyLogEntity.setApplicationFormCode(t.getApplicationFormCode());
        issuePolicyLogEntity.setPolicyNo(t.getPolicyNo());
        issuePolicyLogEntity.setType("1");
        issuePolicyLogEntity.setStatus(consumeStatus);
        issuePolicyLogEntity.setCreateTime(currentTime);
        issuePolicyLogEntity.setUpdateTime(currentTime);
        issuePolicyLogEntity.setProCode(t.getProCode());
        issuePolicyLogEntity.setMainType(t.getMainType());
        issuePolicyLogEntity.setTimes(0);
        issuePolicyLogEntity.setIfCode(t.getIfCode());
        //获取到组装的报文
        String method = myMapMethod.get(t.getIfCode());
        String info = null;
        try {
            Object obj = Class.forName("com.jt.www.job.issue.CheckIssueMQRecordTaskTest").newInstance();
            Class clazz = obj.getClass();
            Method mothods = clazz.getDeclaredMethod(method, IssueRecordEntity.class);
            info = (String) mothods.invoke(obj, t);
        } catch (Exception e) {
            e.printStackTrace();
        }
        issuePolicyLogEntity.setParam(info);
        issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
        t.setSendStatus("2");
        issueRecordEntityMapper.updateByPrimaryKeySelective(t);
    }


    //公用解析方法,获取需要的属性
    public Element analysisXml(String respPacket) {
        //解析mq里面的值
        Element rootElement = null;
        try {
            Document doc = DocumentHelper.parseText(respPacket);
            rootElement = doc.getRootElement();

        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return rootElement;
    }

    //华泰组装报文
    public String infoXmlHt(IssueRecordEntity t) {
        String respPacket = t.getResPacket();
        Element element = analysisXml(respPacket);
        String policyURL = element.element("policyURL").getStringValue();
        // 组装报文
        Document doc = DocumentHelper.createDocument();
        Element info = doc.addElement("body");
        info.addElement("url").addText(policyURL);
        return info.asXML();
    }

    //1实责（全国职业院校学生实习责任保险）  2校责（校方责任保险）
    public String infoXmlXZANDSZ(IssueRecordEntity t) {
        Document doc = DocumentHelper.createDocument();
        Element info = doc.addElement("POLICYNO");
        info.addText(t.getPolicyNo());
        return info.asXML();
    }

    //学生安责组装报文
    public String infoXmlXZ(IssueRecordEntity t) {
        // 组装报文
        Document doc = DocumentHelper.createDocument();
        Element info = doc.addElement("Message");
        doc.setRootElement(info);
        Element body = info.addElement("Body");
        Element policies = body.addElement("Policies");
        policies.addElement("ApplicationFormCode").addText(t.getApplicationFormCode());
        policies.addElement("PolicyNo").addText(t.getPolicyNo());
        policies.addElement("CompanyCode").addText(t.getCompanyCode());
        return info.asXML();
    }

    //云南4个险种组装报文
    public String infoXmlYNFJ(IssueRecordEntity t) {
        String respPacket = t.getResPacket();
        Element element = analysisXml(respPacket);
        String url = element.element("Body").element("Apply").element("PolicyImage").getStringValue();
        // 拼装下载报文
        Document doc = DocumentHelper.createDocument();
        Element info = doc.addElement("Body");
        info.addElement("url").addText(url);
        return info.asXML();
    }

    //山东组装报文
    public String infoXmlSD(IssueRecordEntity t) {
        String respPacket = t.getResPacket();
        Element element = analysisXml(respPacket);
        String url = "";
        try {
            Element elements = element.element("body").element("apply");
            // 排除 批单的信息
            if (elements != null) {
                url = elements.element("electricalDocument").getStringValue();
                // 拼装下载报文
                Document doc = DocumentHelper.createDocument();
                Element info = doc.addElement("body");
                info.addElement("url").addText(url);
                return info.asXML();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //阳光财产安责保护伞
    public String infoXmlAZBHS(IssueRecordEntity t) {
        String respPacket = t.getResPacket();
        try {
            Element element = analysisXml(respPacket);
            Element elements = element.element("Body").element("Apply");
            // 排除无返回结果的报文
            if (elements != null) {
                // 拼装下载报文
                Document doc = DocumentHelper.createDocument();
                Element info = doc.addElement("data");
                info.addElement("policyNo").addText(t.getPolicyNo());
                return info.asXML();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //食品险
    public String infoXmlSPX(IssueRecordEntity t) {
        String respPacket = t.getResPacket();
        try {
            Element element = analysisXml(respPacket);
            Element elements = element.element("Body").element("Apply");
            // 排除无返回结果的报文
            if (elements != null) {
                String policyUrl = elements.element("PolicyUrl").getStringValue();
                // 拼装下载报文
                Map<String, String> map = new HashMap<>();
                map.put("ApplicationFormCode", t.getApplicationFormCode());
                map.put("url", policyUrl);
                String param = JsonUtils.toJson(map);
                return param;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String infoXmlXZXPX(IssueRecordEntity t) {
        String respPacket = t.getResPacket();
        String reqPacket = t.getReqPacket();
        try {
            Element element = analysisXml(respPacket);
            Element elements = element.element("body").element("PolicyApplyResponse");
            // 排除无返回结果的报文
            if (elements != null) {
                Document reqPacketDoc = DocumentHelper.parseText(reqPacket);
                Element reqRootElement = reqPacketDoc.getRootElement();
                // 108001 代表徐州学平意外险， 107001 代表徐州监护人责任险
                String transactionCode = reqRootElement.element("head").element("transactionCode").getStringValue();
                //流水号
                String seqNo = Long.toString(Math.abs(new Random().nextLong()));
                // 拼装下载报文
                Document paramDoc = DocumentHelper.createDocument();
                Element info = paramDoc.addElement("request");
                Element head = info.addElement("head");
                //转换编码
                //transactionCode = 108001(代表徐州学平意外险) 调用数据交换平台下载电子保单时传输编码为：108005
                //transactionCode = 107001(代表徐州学平意外险) 调用数据交换平台下载电子保单时传输编码为：107003
                if ("108001".equals(transactionCode)) {
                    head.addElement("partnerCode");
                    head.addElement("messageId").addText(seqNo);//流水号
                    head.addElement("transactionCode").addText("108005");// 意外险标示 108005:代表徐州学平意外险
                    head.addElement("transactionEffectiveDate").addText(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                    head.addElement("user");
                    head.addElement("password");
                    Element body = info.addElement("body");
                    Element epolicyInfoReprint = body.addElement("epolicyInfoReprint");
                    epolicyInfoReprint.addElement("policyNo").addText(t.getPolicyNo());
                    epolicyInfoReprint.addElement("messageFlag");
                    epolicyInfoReprint.addElement("emailFlag");
                    epolicyInfoReprint.addElement("returnPDFFlag");
                } else if ("107001".equals(transactionCode)) {
                    head.addElement("partnerCode");
                    head.addElement("transactionCode").addText("107003");// 意外险标示 107003:代表徐州监护人责任险
                    head.addElement("messageId").addText(seqNo);//流水号
                    head.addElement("transactionEffectiveDate").addText(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                    head.addElement("user");
                    head.addElement("password");
                    Element body = info.addElement("body");
                    Element entity = body.addElement("entity");
                    entity.addElement("plcNo").addText(t.getPolicyNo());
                    entity.addElement("elcMsgFlag");
                    entity.addElement("elcMobile");
                    entity.addElement("elcEmlFlag");
                    entity.addElement("elcEmail");
                    entity.addElement("returnPDF");
                }
                return info.asXML();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //处理统一格式的电子保单
    public String infoXmlEpolicy(IssueRecordEntity t) {
        String respPacket = t.getResPacket();
        String reqPacket = t.getReqPacket();
        try {
            Element element = analysisXml(respPacket);
            Element elements = element.element("MAIN");
            // 排除无返回结果的报文
            if (elements != null) {
                String policyUrl = element.element("EURL").getStringValue();
                // 拼装下载报文
                Document edoc = DocumentHelper.createDocument();
                Element info = edoc.addElement("body");
                info.addElement("url").addText(policyUrl);
                String xml = info.asXML().replaceAll("&amp;", "&");
                return xml;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //食品险（太平）
    public String infoXmlSPXTP(IssueRecordEntity t) {
        String respPacket = t.getResPacket();
        String reqPacket = t.getReqPacket();
        try {
            Element element = analysisXml(respPacket);
            Element elements = element.element("Body");
            // 排除无返回结果的报文
            if (elements != null) {
                String policyUrl = elements.element("PolicyUrl").getStringValue();
                // 拼装下载报文
                Document epolicyDoc = DocumentHelper.createDocument();
                Element info = epolicyDoc.addElement("body");
                info.addElement("url").addText(policyUrl);
                return info.asXML();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String infoXmlSZXZDD(IssueRecordEntity t) {
        String respPacket = t.getResPacket();
        String reqPacket = t.getReqPacket();
        String url = "";
        try {
            Element element = analysisXml(respPacket);
            List<Element> respChildElements = element.element("Body").elements();
            for (Element child : respChildElements) {

                String policyNo = child.element("PolicyNo").getStringValue();
                if (t.getPolicyNo().equals(policyNo)) {
                    url = child.element("PolicyUrl").getStringValue();
                }
            }
            // 组装报文
            Map<String, String> map = new HashMap<>();
            map.put("ApplicationFormCode", t.getApplicationFormCode());
            map.put("url", url);
            String param = JsonUtils.toJson(map);
            return param;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String infoXmlSZXZ(IssueRecordEntity t) {
        String respPacket = t.getResPacket();
        String reqPacket = t.getReqPacket();
        String url = "";
        try {
            Element element = analysisXml(respPacket);
            List<Element> respChildElements = element.element("Body").elements();
            for (Element child : respChildElements) {
                if (t.getIfCode().equals(ZH_SZ_XZ_POLICY.getIfCode())) {
                    String policyNo = child.element("PolicyCode").getStringValue();
                    if (t.getPolicyNo().equals(policyNo)) {
                        url = child.element("PolicyUrl").getStringValue();
                    }
                } else {
                    String policyNo = child.element("PolicyNo").getStringValue();
                    if (t.getPolicyNo().equals(policyNo)) {
                        url = child.element("PolicyUrl").getStringValue();
                    }
                }
            }
            //添加url处理
            url = url.replaceAll("&amp;", "&");
            // 组装报文
            Document doc = DocumentHelper.createDocument();
            Element info = doc.addElement("body");
            info.addElement("url").addText(url);
            return info.asXML();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //实责 校责 阳光
    public String infoXmlXSZAndXZ(IssueRecordEntity t) {
        Document doc = DocumentHelper.createDocument();
        Element info = doc.addElement("INSURENCEINFO").addElement("POLICYNO");
        return info.asXML();
    }

}
